import { Component, OnInit, Input } from '@angular/core';
// 导入表单相关：表单验证、表单构建、表单组
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { ContainerService } from 'src/app/core/service/container.service';

@Component({
  selector: 'app-container-modal',
  templateUrl: './container-modal.component.html',
  styleUrls: ['./container-modal.component.scss']
})

export class ContainerModalComponent implements OnInit {
  @Input() title: string;
  @Input() subtitle: string;
  data = {};
  containerForm: FormGroup;

  constructor(
    private modal: NzModalRef,
    private message: NzMessageService,
    private containerService: ContainerService,
    fb: FormBuilder
  ) {
    this.containerForm = fb.group({
      containerName: [null, Validators.required],
      version: [null, Validators.required],
      releaseDate: [null, Validators.required]
    });
  }

  addContainer(): void {
    console.log(this.containerForm.controls);
    // tslint:disable-next-line:forin
    for (const c in this.containerForm.controls) {
      this.containerForm.controls[c].markAsTouched();
    }


    if (this.containerForm.valid) {
      this.data = {
        name: this.containerForm.value.containerName,
        version: this.containerForm.value.version,
        release_date: this.containerForm.value.releaseDate,
        baseline_ids: [{ baseline_id: '1' }],
        jdk: '',
        source: '1',
        grade: '',
        cves: '0',
        cnnvds: '0',
        modify_time: '2019-03-19 06:03:33',
        create_time: '2019-03-19 06:03:33',
        group_uuid: ''
      };
      console.log(' ====this.data === ', this.data);
      this.addService(this.data);

    } else {
      this.message.error('表单校验失败', { nzDuration: 10000 });
    }
  }

  destroyModal(): void {
    this.modal.destroy({ data: 'this the result data' });
  }

  private addService(data: any) {
    this.containerService.addContainer(this.data).subscribe((addResult) => {
      // this.result = result;   // 返回的结果
      console.log('==result==', addResult);
      if (addResult.status === 1) {
        this.message.success('添加成功!', {
          nzDuration: 10000
        });
        this.modal.destroy({ data: 'this the result data' });
      } else {
        this.message.error('添加失败!请检查后重新填写', {
          nzDuration: 10000
        });
      }
    });
  }

  ngOnInit() {
  }

}
